package com.ruowei.modules.wxpay.web.task;

import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ruowei.modules.foodOrder.domain.QOrder;
import com.ruowei.modules.foodOrder.domain.enumeration.FlowType;
import com.ruowei.modules.foodOrder.domain.enumeration.OrderStatus;
import com.ruowei.modules.foodOrder.repository.OrderRepository;
import com.ruowei.modules.foodOrder.service.LifeCycleService;
import com.ruowei.modules.foodOrder.service.MerchantService;
import com.ruowei.modules.foodOrder.service.PaymentFlowService;
import com.ruowei.modules.webSocket.domain.enumeration.MessageType;
import com.ruowei.modules.webSocket.domain.enumeration.ReceiverType;
import com.ruowei.modules.webSocket.domain.enumeration.SenderType;
import com.ruowei.modules.webSocket.service.MessagePushService;
import com.ruowei.modules.wxpay.service.WeChatPayService;
import com.ruowei.modules.wxpay.utils.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
//处理支付订单定时任务
public class HandlePaidOrderTask {
    private final QOrder qOrder = QOrder.order;

    private final JPAQueryFactory jpaQueryFactory;
    private final WeChatPayService payService;
    private final OrderRepository orderRepository;
    private final LifeCycleService lifeCycleService;
    private final MessagePushService messagePushService;
    private final PaymentFlowService paymentFlowService;
    private final MerchantService merchantService;

    public HandlePaidOrderTask(JPAQueryFactory jpaQueryFactory, WeChatPayService payService,
                               OrderRepository orderRepository, LifeCycleService lifeCycleService,
                               MessagePushService messagePushService, PaymentFlowService paymentFlowService, MerchantService merchantService) {
        this.jpaQueryFactory = jpaQueryFactory;
        this.payService = payService;
        this.orderRepository = orderRepository;
        this.lifeCycleService = lifeCycleService;
        this.messagePushService = messagePushService;
        this.paymentFlowService = paymentFlowService;
        this.merchantService = merchantService;
    }

    /**
     * @apiNote 每3秒执行一次  处理已支付的订单 查询支付状态 更新状态
     * 支付成功或失败支付的时候就能知道，这里只是把系统的订单状态更新
     * 这里跟微信统一下单回调接口功能一样
     * @author 董兴
     * @date 2020年11月26日
     */
    //@Scheduled(cron = "*/5 * * * * ?")
    public void handlePaidOrder() {
        jpaQueryFactory.selectFrom(qOrder)
            .where(qOrder.status.in(OrderStatus.TO_BE_PAID))
            .fetch()
            .forEach(order -> {
                try {
                    Map<String, String> map = payService.queryOrder(order.getOrderCode());
                    if (map.get("return_code").equals("SUCCESS") &&
                        map.get("result_code").equals("SUCCESS") &&
                        map.get("trade_state").equals("SUCCESS")) {
                        //如果订单支付成功 更新订单状态
                        order.setStatus(OrderStatus.TO_BE_RECEIVED);
                        order.setPaymentTime(Instant.now());
                        order.setUpdateTime(Instant.now());
                        orderRepository.saveAndFlush(order);
                        //保存流水
                        paymentFlowService.savePaymentFlow(order.getOrderCode(),
                            null,
                            order.getMemberCode(),
                            FlowType.ORDER,
                            order.getMerchantCode(),
                            merchantService.getMerchantNameBy(order.getMerchantCode()),
                            order.getPayAmount());

                        lifeCycleService.saveLifeCycle(order.getOrderCode(), null, "支付成功", "支付成功", false);

                        //给商家发消息
                        Map<String, String> customMessage = new HashMap<>();
                        customMessage.put("id", String.valueOf(order.getId()));
                        customMessage.put("orderCode", order.getOrderCode());
                        messagePushService.pushMessage(SenderType.SYSTEM,
                            null,
                            order.getMerchantCode(),
                            MessageType.FOOD_ORDER,
                            true,
                            "新的订单",
                            "您有新的订单",
                            customMessage,
                            ReceiverType.MERCHANT_APP);
                    } else {
                        //订单未支付或支付失败
                        if (!WXPayUtil.mapToXml(map).contains("订单未支付")) {
                            log.error(WXPayUtil.mapToXml(map));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
    }
}
